<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px">
    
      <el-row>
        <el-col :span="12">
          <el-form-item label="医师" prop="doctorId">
            <el-select
              v-model="formData.doctorId"
              placeholder="请选择医师"
              clearable
              disabled
            >
              <el-option
                v-for="doctor in doctorList"
                :key="doctor.id"
                :label="doctor.nickname"
                :value="doctor.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="病人" prop="patientsId">
            <el-select
              v-model="formData.patientsId"
              placeholder="请选择病人"
              clearable
              disabled
            >
              <el-option
                v-for="patient in patientList"
                :key="patient.id"
                :label="patient.nickname"
                :value="patient.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>

        <el-col :span="12">
          <el-form-item label="就诊日期" prop="date">
            <el-date-picker
              v-model="formData.date"
              type="date"
              :placeholder="formData.date? safeDateFormatter(formData.date) : '请选择日期'"
              class="!w-120px"
              clearable
              value-format="YYYY-MM-DD"
              disabled
          />
          </el-form-item>

        </el-col>

        <el-col :span="12">
          <el-form-item label="时段" prop="period">
            <el-select
              v-model="formData.period"
              placeholder="请选择时段"
              clearable
              disabled
            >
              <el-option
                v-for="dict in getIntDictOptions
                (DICT_TYPE.MEDICAL_REGISTER_PERIOD)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row>

        <el-col :span="12" disabled>
          <el-form-item label="挂号状态" prop="registerStatus">
            <el-select
              v-model="formData.registerStatus"
              placeholder="请选择时段"
              clearable
              disabled
            >
              <el-option
                v-for="dict in getIntDictOptions
                (DICT_TYPE.MEDICAL_REGISTER_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row>
        <el-col>
          <el-form-item label="病人描述" prop="description">
            <el-input
              v-model="formData.description"
              placeholder="请输入病人描述"
            />
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict';
import * as RegisterApi from '@/api/medical/register'
import * as DoctorApi from '@/api/medical/doctor'
import * as PatientApi from '@/api/medical/patient'
import { FormRules } from 'element-plus'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
dayjs.extend(utc)


import { safeDateFormatter } from '@/utils/formatTime'



defineOptions({ name: 'MedicalRecordForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const doctorList = ref([])// 医师列表
const patientList = ref([])// 病人列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  doctorId: '',
  patientsId: '',
  deptId: '',
  date: '' as string | Date, // 明确类型
  consultingTime: '',
  period: undefined,
  cost: undefined,
  registerStatus: undefined,
  description: '',
  createTime: ''
})
const formRules = reactive<FormRules>({
  date: [{required: true, message: '请选择日期'}]
})
const formRef = ref() // 表单 Ref


/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  getDoctorList()
  getPatientList()

  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    // const response = await RegisterApi.getRegister(id)
    // formData.value = response
    // formLoading.value = false
    try {
      const response = await RegisterApi.getRegister(id)
      // 确保日期格式正确
      formData.value = {
      ...response,
      date: response.date ? dayjs(response.date).utc().toDate() : ''
    }
    } finally {
      formLoading.value = false
    }
  }

}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RegisterApi.MRegisterVO
    if (formType.value === 'create') {
      await RegisterApi.createRegister(data)
      message.success(t('common.createSuccess'))
    } else {
      await RegisterApi.updateRegister(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    doctorId: '',
    patientsId: '',
    deptId: '',
    date: '',
    consultingTime: '',
    period: undefined,
    cost: undefined,
    registerStatus: undefined,
    description: '',
    createTime: ''
  }
  formRef.value?.resetFields()
}


/**获取医师列表 */
const getDoctorList = async () => {
  const response = await DoctorApi.getDoctorList()
  console.log('response:', response)
  doctorList.value = response
}

/**获取病人列表 */
const getPatientList = async () => {
  const response = await PatientApi.getPatientList()
  console.log('response:', response)
  patientList.value = response
}
</script>